package com.yaolong.api.modules.opms.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yaolong.api.modules.opms.entity.FixResident;
import com.yaolong.api.modules.opms.entity.OpmsFixFamilyInfo;
import com.yaolong.api.modules.opms.dao.OpmsFixFamilyInfoDao;
import com.yaolong.api.modules.opms.service.FixResidentService;
import com.yaolong.api.modules.opms.service.OpmsFixFamilyInfoService;
import com.yaolong.api.modules.sys.domain.SysUser;
import com.yaolong.api.modules.sys.domain.SysUserInfo;
import com.yaolong.api.modules.sys.dto.RoleInfoDto;
import com.yaolong.api.modules.sys.dto.UserInfoDto;
import com.yaolong.api.modules.sys.po.RoleInfo;
import com.yaolong.api.modules.sys.service.ISysRoleService;
import com.yaolong.api.modules.sys.service.ISysUserInfoService;
import com.yaolong.api.modules.sys.service.ISysUserRoleService;
import com.yaolong.api.modules.sys.service.ISysUserService;
import com.yaolong.api.modules.sys.vo.AllotRoleParam;
import com.yaolong.api.modules.sys.vo.UserParams;
import com.yaolong.api.modules.utils.CheckRoleUtils;
import com.yaolong.commons.base2.BaseServiceImpl;
import com.yaolong.commons.constant.GlobConstant;
import com.yaolong.commons.exceptions.BusinessException;
import com.yaolong.commons.response.ResponseCode;
import com.yaolong.commons.utils.MapperUtils;
import com.yaolong.commons.utils.ObjectTool;
import com.yaolong.commons.web.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 常住家庭信息表 服务实现类
 * </p>
 *
 * @author yaolonga
 * @version v1.0.0
 * @since 2023-02-19
 */
@Service
public class OpmsFixFamilyInfoServiceImpl extends BaseServiceImpl<OpmsFixFamilyInfoDao, OpmsFixFamilyInfo> implements OpmsFixFamilyInfoService {

    @Autowired
    private ISysUserService iSysUserService;

    @Autowired
    private ISysUserInfoService iSysUserInfoService;

    @Autowired
    private FixResidentService fixResidentService;


    @Override
    @Transactional(rollbackFor = BusinessException.class)
    public boolean create(OpmsFixFamilyInfo domain) {
        /**
         * 创建家庭的同时需要分配一个账户并划分角色和居民
         * 居民
         * */
        try {
            /** 户口本号作为账号*/
            UserParams userParams = new UserParams();
            userParams.setUsername(domain.getHkbNumber());
            userParams.setStatus(false);//启用
            List<Long> list = new ArrayList<>();
            list.add(8L);
            userParams.setRoles(list);
            //验证用户是否已经存在
            SysUser sysUser1 = iSysUserService.getOne(new LambdaQueryWrapper<SysUser>().eq(SysUser::getUsername, userParams.getUsername()));
            if (!ObjectTool.isEmpty(sysUser1)) {
                throw new BusinessException(ResponseCode.USER_HAS_EXISTED);
            }
            //添加用户
            SysUser sysUser = new SysUser();
            sysUser.setPassword(new BCryptPasswordEncoder().encode(GlobConstant.DEFAULT_PASSWORD));
            sysUser.setUsername(userParams.getUsername());
            sysUser.setStatus(userParams.getStatus());
            iSysUserService.save(sysUser);
            //添加用户信息
            SysUserInfo sysUserInfo = new SysUserInfo();
            sysUserInfo.setUserId(sysUser.getId());
            sysUserInfo.setUsername(sysUser.getUsername());
            sysUserInfo.setRealName(domain.getHouseholder());//真实名字：户主名字
            sysUserInfo.setRemark("家庭账号");
            iSysUserInfoService.create(sysUserInfo);
            //添加角色信息（分配角色）
            AllotRoleParam allotRoleParam = new AllotRoleParam();
            allotRoleParam.setUserId(sysUser.getId());
            allotRoleParam.setRoleIds(userParams.getRoles());
            iSysUserService.allotRole(allotRoleParam);
            domain.setUserId(sysUser.getId());
            /** 添加居民（户主）*/
            FixResident fixResident = new FixResident();
            fixResident.setName(domain.getHouseholder());//姓名
            fixResident.setHouseholder(domain.getHouseholder());//户主
            fixResident.setHkbNumber(domain.getHkbNumber());//户口本号
            fixResident.setContactNumber(domain.getContactNumber());//联系电话
            fixResident.setGroupNumber(domain.getGroupNumber());//组号
            fixResident.setHkType(domain.getHkType());//户口类型
            fixResident.setBirthPlace(domain.getAddress());//家庭地址
            fixResident.setHouseholderRelation("本人");
            List<FixResident> fixResidentList = fixResidentService.list(fixResident);
            if (ObjectTool.isEmpty(fixResidentList)) {
                fixResidentService.save(fixResident);
                domain.setHouseholderId(fixResident.getId());//存入户主id
                //添加家庭
                super.create(domain);
                fixResident.setFamilyId(domain.getId());//存入家庭id
                boolean update = fixResidentService.lambdaUpdate().eq(FixResident::getId, fixResident.getId()).set(FixResident::getFamilyId, domain.getId()).update();
                System.out.println(update);
                //fixResidentService.update(fixResident);//更新
            } else {
                domain.setHouseholderId(fixResidentList.get(0).getId());//存入户主id
                //添加家庭
                super.save(domain);
                fixResidentList.get(0).setFamilyId(domain.getId());//存入家庭id
                fixResidentService.update(fixResidentList.get(0));//更新
            }

            return true;
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException("创建家庭信息失败，请联系管理员！");
        }
    }

    @Override
    public IPage<OpmsFixFamilyInfo> page(int current, int size, OpmsFixFamilyInfo domain) {
        IPage<OpmsFixFamilyInfo> page = new Page<>(current, size);
        //根据角色获取家庭id信息
        UserInfoDto userInfoDto = iSysUserInfoService.userInfoByContext();
        List<RoleInfo> roleInfos = MapperUtils.copyList(userInfoDto.getRoles(), RoleInfo.class);
        Long userId = userInfoDto.getUserId();
        //true:含有管理员权限 或者 审核员权限
        boolean flag = CheckRoleUtils.checkRole(roleInfos);
        //居民角色
        if (!flag) {
            //存入登录账号id
            domain.setUserId(userId);
        }
        return lambdaQuery()
                .eq(!ObjectUtils.isEmpty(domain.getUserId()), OpmsFixFamilyInfo::getUserId, domain.getUserId())
                .like(!ObjectUtils.isEmpty(domain.getHkType()), OpmsFixFamilyInfo::getHkType, domain.getHkType())
                .like(!ObjectUtils.isEmpty(domain.getHouseholder()), OpmsFixFamilyInfo::getHouseholder, domain.getHouseholder())
                .like(!ObjectUtils.isEmpty(domain.getAddress()), OpmsFixFamilyInfo::getAddress, domain.getAddress())
                .page(page);
    }

    @Override
    public List<OpmsFixFamilyInfo> list(OpmsFixFamilyInfo domain) {
        //根据角色获取信息
        UserInfoDto userInfoDto = iSysUserInfoService.userInfoByContext();
        List<RoleInfoDto> roles = userInfoDto.getRoles();
        return lambdaQuery()
                .eq(!ObjectUtils.isEmpty(domain.getUserId()), OpmsFixFamilyInfo::getUserId, domain.getUserId())
                .like(!ObjectUtils.isEmpty(domain.getHkType()), OpmsFixFamilyInfo::getHkType, domain.getHkType())
                .like(!ObjectUtils.isEmpty(domain.getHouseholder()), OpmsFixFamilyInfo::getHouseholder, domain.getHouseholder())
                .like(!ObjectUtils.isEmpty(domain.getAddress()), OpmsFixFamilyInfo::getAddress, domain.getAddress())
                .list();
    }

    /**
     * 导出
     */
    @Override
    public boolean exportFile(List<Long> ids) {
        return super.exportFile(ids);
    }

    @Override
    public boolean importFile(MultipartFile file) {
        return super.importFile(file);
    }
}
